package com.zhangjk.util;


import com.zhangjk.enums.AppConstant;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;

import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang.time.DateUtils;

import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * JWT Token 和实体的相互转化方法
 *
 * 2018-10-23
 * hsc
 */
@Component
public class TokenUtil {
    //jwt token密码


    //有效时间（毫秒）
    //@Value("${chis.datasecurity.validatetime}")


    public String createJwtString(JwtToken jt) {
        Date nowDate = new Date();
        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject("Sub")
                .claim("openid", jt.getOpenid())
                .claim("session_key", jt.getSession_key())
                .setIssuedAt(nowDate)
                .setExpiration(DateUtils.addMilliseconds(nowDate, AppConstant.validateTime))
                .signWith(SignatureAlgorithm.HS256, AppConstant.KEY)
                .compact();
    }

    public JwtToken getJwtInfo(String jwt) {
        Claims claims = Jwts.parser()
                .setSigningKey(AppConstant.KEY)
                .parseClaimsJws(jwt)
                .getBody();
        JwtToken jt = new JwtToken();
        jt.setOpenid(claims.get("openid").toString());
        jt.setSession_key(claims.get("session_key").toString());
        jt.setExpiration(claims.getExpiration());

        return jt;
    }


}
